package com.anosine.gpsl.android.ui.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.format.Formatter;
import android.view.*;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.anosine.gpsl.android.AppConstants;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.entity.UpdataInfoBean;
import com.anosine.gpsl.android.util.BundleKey;
import com.anosine.gpsl.android.util.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;


import java.io.File;

/**
 * @Title: ShowDownloadProgressDlg
 * @Package com.anosine.gpsl.android.ui.fragment
 * @Description: 
 * @author: sunny
 * @date: 2015-11-25
 * @version V1.0
 */
public class ShowDownloadProgressDlg extends DialogFragment implements View.OnClickListener, DialogInterface.OnKeyListener {

    private UpdataInfoBean mInfo;
    private final String mSaveApkName="lovecar1.apk";
    /**
     * 方法名：showDlg(FragmentManager manager, UpdataInfoBean info)
     * 功能：显示弹框
     * 参数：FragmentManager manager 管理fragments, UpdataInfoBean info 更新信息的bean
     * 返回值：DialogFragment
     * */
    public static DialogFragment showDlg(FragmentManager manager, UpdataInfoBean info) {
        ShowDownloadProgressDlg dlg = new ShowDownloadProgressDlg();
        Bundle args=new Bundle();
        args.putSerializable(BundleKey.TAG_SCENERY_DATA, info);
        dlg.setArguments(args);
        dlg.show(manager, null);
        return dlg;
    }
    /**
     * 方法名：onCreate(Bundle savedInstanceState)
     * 功能：初始化  OnCreate()函数主要是用来响应WM_CREATE消息的 
     * 参数：Bundle savedInstanceState
     * 返回值：无
     * */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.custom_dlg);
    }
    /**
     * 方法名：onSaveInstanceState(Bundle outState)
     * 功能：覆盖onSaveInstanceState()方法来保存（Activity的）附件信息 onSaveInstanceState() 只有在系统即将要自动清理销毁Activity或Fragment前才会调用
     * 参数：Bundle outState 存储的数据
     * 返回值：无*/
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(BundleKey.TAG_SCENERY_DATA, mInfo);
    }

    private TextView mTvShowInfo;
    private TextView mTvUpdateInfo;

    private ProgressBar mPbShow;
    private HttpHandler handler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle args=getArguments()!=null? getArguments(): savedInstanceState;
        if (args!=null){
            mInfo= (UpdataInfoBean) args.getSerializable(BundleKey.TAG_SCENERY_DATA);
        }
        View view = inflater.inflate(R.layout.dlg_show_download_progressbar, container);
        view.findViewById(R.id.btn_confirm_dlg_cancel).setOnClickListener(this);
        mPbShow= (ProgressBar) view.findViewById(R.id.pb_dlg_update_show);
        mTvShowInfo= (TextView) view.findViewById(R.id.tv_dlg_update_show);
        mTvUpdateInfo= (TextView) view.findViewById(R.id.tv_dlg_update_info);
        if (mInfo!=null){
            mTvUpdateInfo.setText(mInfo.getDescription());
        }
        beginDownload();
        return view;
    }
    /**
	 * 文件名：beginDownload(final Context context)
	 *  功能：开始下载apk 
	 *  参数：Context context 上下文 
	 * @return 无
	 * */
    private void beginDownload() {
        File f = new File(AppConstants.PATH_APK);
        if (!f.exists()) {
            f.mkdirs();
        }
        String savePath=AppConstants.PATH_APK + mSaveApkName ;

        RequestCallBack<File> response=new RequestCallBack<File>() {
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                if (getActivity()!=null){
                    String speed = String.format("%1s/%2s", Formatter.formatFileSize(getActivity(), current), Formatter.formatFileSize(getActivity(), total));
                    mTvShowInfo.setText(speed);
                    int progress = 0;
                    if (total != 0) {
                        progress = (int) (1.0f * current / total * 100);
                    }
                    mPbShow.setProgress(progress);
                }
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                try {
                    String filePath=responseInfo.result.getPath();
                    File file=new File(filePath);
                    if (file.exists()&& file.isFile()){
                        installApk(file);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastHelper.toast(msg);
            }
        };

        response.setRate(200);
        HttpUtils http = new HttpUtils();
        handler = http.download(mInfo.getUrl(), savePath, false, false, response);

    }



    protected void installApk(File file) {
        if (getActivity()!=null){
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
            getActivity().startActivity(intent);
            dismiss();
        }
    }

    @Override
    public void onActivityCreated(Bundle arg0) {
        super.onActivityCreated(arg0);
        WindowManager.LayoutParams layoutParams = getDialog().getWindow().getAttributes();
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int mScreenWidth = wm.getDefaultDisplay().getWidth();
        layoutParams.width = (int)(mScreenWidth*0.9f) ;
        getDialog().setCanceledOnTouchOutside(false) ;
        getDialog().setOnKeyListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_confirm_dlg_cancel:
                if (handler!=null && !handler.isCancelled()){
                    handler.cancel();
                }
                dismiss();
                break;
        }
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancel(dialog);
        dismissSetInfoNull();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        dismissSetInfoNull();
    }

    private void dismissSetInfoNull() {
        if (handler!=null && !handler.isCancelled()){
            handler.cancel();
        }
    }

    @Override
    public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            return true;
        }
        return false;
    }
}
